﻿using AutoMapper;
using B.S.BaseData.Api.Read.Command.RBAC;
using B.S.BaseData.ErrorCode;
using B.S.BaseData.Infrastructure.Interface;
using B.S.BataBase.Domain.DTO;
using B.S.BataBase.Domain.RBAC;
using MediatR;
using System.Linq;
using System.Threading.Tasks;

namespace B.S.BaseData.Api.Read.CommandHandler.RBAC
{
    public class RoleShowCommandHandler : IRequestHandler<RoleShowCommand, APIResult<ApiPaging<RoleDTO>>>
    {
        private readonly IBaseRepository<RoleModel> _rolerepository;
        private readonly IBaseRepository<RolePermissionsModel> _rolepubrolerepository;
        private readonly IBaseRepository<PermissionsModel> _permissrepository;
        private readonly IMapper _mapper;
        public RoleShowCommandHandler(IBaseRepository<RoleModel> rolerepository, IBaseRepository<RolePermissionsModel> rolepubrolerepository, IMapper mapper, IBaseRepository<PermissionsModel> permissrepository)
        {
            _rolerepository = rolerepository;
            _rolepubrolerepository = rolepubrolerepository;
            _mapper = mapper;
            _permissrepository = permissrepository;
        }

        public async Task<APIResult<ApiPaging<RoleDTO>>> Handle(RoleShowCommand request, CancellationToken cancellationToken)
        {
            APIResult<ApiPaging<RoleDTO>> result=new APIResult<ApiPaging<RoleDTO>>();
            result.Code=ApiEnum.Success;
            result.Msg = "角色列表显示成功";
            var list = _rolerepository.GetAll().Where(x=>x.IsDeleted==false);
            
            if(request.roleName!=null)
            {
                list = list.Where(x=>x.RoleName.Contains(request.roleName));
            }
            var res = _mapper.Map<List<RoleDTO>>(list);
            foreach (var item in res)
            {
                var data =_rolepubrolerepository.GetAll().Where(x=>x.RoleId==item.Id).Select(x=>x.PermissionsId).ToList();
                item.QxName=await GetQxName(data);
                item.QxList=data;
            }
            ApiPaging<RoleDTO> paging=new ApiPaging<RoleDTO>();
            var totaCount=res.Count();
            var pageCount = (int)Math.Ceiling(totaCount*1.0/request.pageSize);
            paging.TotalPage = pageCount;
            paging.Total=totaCount;
            paging.PageData= res.OrderByDescending(x=>x.RoleCreateTime).Skip((request.pageIndex-1)*request.pageSize).Take(request.pageSize).ToList();
            result.Data = paging;
            return await Task.FromResult(result);
        }
        /// <summary>
        /// 获取权限
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public async Task<string> GetQxName(List<long> ids)
        {
            string a = "";
            foreach (var id in ids)
            {
                a += (await _permissrepository.GetValues(x=>x.Id==id)).PermissionsName+",";
            }
            return a.TrimEnd(',');
        }
    }
}
